<script lang="ts" setup name="planEdit">
import { onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
// import { getYMD } from "@/utils/date";
import {
  checkStockPlan,
  createStockPlan,
  editStockPlan,
  getDetailPlanPageList,
  getInventoryGoodsList,
  getStockPlanEdit,
  getStorehouseList,
  getWaresCategoryList
} from "@/api/modules/inventory";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance } from "@/components/ProTable/interface";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import { detailTypeNameType } from "@/utils/serviceDict";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

// const typeScopeList: stockSPlanStatus = [
//   { label: "单品盘点", value: 1 },
//   { label: "全场盘点", value: 2 }
// ];
/* 仓库start */
const storeList = ref<any[]>([]);
// const defaultHouserId = ref(null);
const onShowStore = async () => {
  const res = await getStorehouseList({});
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      stockPlanForm.value.houseId = v.id;
    }
  });
};
const selectChange = () => {
  stockPlanForm.value.inventoryplandetailList = [];
};

// 主数据，发请求和渲染截面数据
const stockPlanForm = ref<any>({
  orderId: 0,
  orderNo: "",
  // corpId: 0,
  // storeId: 0,
  // planType: 1,
  status: 1,
  sysUserId: 0,
  // checkerId: 0,
  checkFlag: false,
  // checkTime: 0,
  // updateTime: 0,
  houseId: 0,
  // createTime: getYMD(),
  remark: "",
  detailType: "",
  isClean: false,
  inventoryplandetailList: []
});
// inventory: {
//   inventorydetailList: []
// }

const houseIdF = ref(null); // 如果是编辑复原仓库是复原数据
const newList = ref([]);
watch(
  () => stockPlanForm.value.houseId,
  () => {
    if (houseIdF.value === stockPlanForm.value.houseId && route.query.id) {
      stockPlanForm.value.inventoryplandetailList = newList.value;
    }
  }
);

const proTable = ref<ProTableInstance>();
// 外层表格的列的每一项
const columns: any[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 100 },
  { prop: "barcode", label: "编码", minWidth: 200 },
  { prop: "name", label: "名称", minWidth: 140 },
  { prop: "categoryName", label: "分类名称", minWidth: 120 },
  { prop: "productName", label: "规格", minWidth: 100 },
  { prop: "quantity", label: "账面数量", minWidth: 80 },
  { prop: "costAmount", label: "账面金额", minWidth: 80 },
  { prop: "price", label: "成本价", minWidth: 80 },
  { prop: "unitName", label: "单位", minWidth: 80 },

  // { prop: "categoryName", label: "原料分类", minWidth: 80 },
  { prop: "realQuantity", label: "实盘数量", minWidth: 80 },
  { prop: "realAmount", label: "实盘金额", minWidth: 80 },
  { prop: "profitLossQuantity", label: "盈亏数量", minWidth: 80 },
  { prop: "profitLossAmount", label: "盈亏金额", minWidth: 80 },
  {
    prop: "detailType",
    label: "盘点结果",
    enum: detailTypeNameType,
    minWidth: 80
  }
  // { prop: "detailTypeName", label: "盘点结果描述", minWidth: 80 }
];

// 打开库存原料弹出层列表
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  if (!stockPlanForm.value.houseId) return ElMessage.error("请先选择仓库");
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "productsId",
    selTags: stockPlanForm.value.inventoryplandetailList
      .filter((age: any) => age.goodsId !== 0)
      .map((i: any) => {
        i.name = i.name;
        i.id = i.productsId;
        return i;
      }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", minWidth: 220 },
      { prop: "name", label: "原料名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 100 },
      // { prop: "posPrice", label: "原料价格", minWidth: 120 }
      { prop: "purPrice", label: "采购价格", minWidth: 120 }
    ],
    apiParams: { houseId: stockPlanForm.value.houseId },
    idName: "goodsCategoryId",
    // 发请求
    treeApi: getWaresCategoryList,
    api: getInventoryGoodsList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
// 选中库存原料
const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        name: im.name,
        id: im.id,
        storeId: im.storeId,
        corpId: im.corpId,
        productsId: im.productsId,
        productName: im.productName,
        goodsId: im.id,
        quantity: im.planQuantity,
        price: im.costPrice,
        barcode: im.barcode,
        unitName: im.unitName,
        categoryName: im.categoryName,
        costAmount: im.costAmount
      };
    });

    list.forEach(v => {
      if (!stockPlanForm.value!.inventoryplandetailList.some((i: any) => i.productsId === v.productsId)) {
        stockPlanForm.value!.inventoryplandetailList.push(v);
      }
    });
  }
};
const delSpecRow = (index: number) => {
  if (stockPlanForm.value.inventoryplandetailList.length <= 1) return ElMessage.error("原料不能少于一条数据");
  stockPlanForm.value.inventoryplandetailList.splice(index, 1);
};

// 😒😒😒😒😒😒判断数据回来是否是可查看还是可编辑，查看禁用不能操作
// const initParam = ref({ id: route.query?.id });
const initParam = reactive({ id: route.query?.id, detailType: stockPlanForm.value.detailType });
const documentStatus = ref<string>("add");
onMounted(async () => {
  onShowStore();
  if (route.query?.id) {
    // , getDetailPlanPageList({ id: route.query.id })
    Promise.all([getStockPlanEdit({ id: route.query.id })])
      .then(res => {
        // console.log(res);
        stockPlanForm.value = JSON.parse(JSON.stringify(res[0].data));
        houseIdF.value = res[0].data.houseId;
        newList.value = res[0].data.inventoryplandetailList;
        if (res[0].data.status === 4) {
          // 编辑
          documentStatus.value = "audited";
        } else {
          // 查看
          documentStatus.value = "edit";
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else {
    documentStatus.value = "add";
  }
});
const onSubmit = async () => {
  if (route.query.id) {
    await editStockPlan(stockPlanForm.value);
    router.push({
      path: "/stock/stockPlanList",
      query: {
        upList: true
      }
    });
  } else {
    if (stockPlanForm.value.inventoryplandetailList < 1) return ElMessage.error("原料明细不能为空");
    await createStockPlan(stockPlanForm.value);
    router.push({
      path: "/stock/stockPlanList",
      query: {
        upList: true
      }
    });
  }
};

const onCheckSubmit = async () => {
  await checkStockPlan({ id: route.query?.id });
  ElMessage.success("成功完成盘点");
  router.push({
    path: "/stock/stockPlanList",
    query: {
      upList: true
    }
  });
};

// 合计数据 start     :summary-method="getSummaries"
// interface SummaryMethodProps<T = Inventory.ResPurchaseList> {
//   columns: TableColumnCtx<T>[];
//   data: T[];
// }
// const getSummaries = (param: SummaryMethodProps) => {
//   console.log(param);
// };
// 处理表格请求回来的数据和合计数组
const summary = ref<any[]>([]);
const dataCallback = (data: any) => {
  summary.value = data.summary;
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};
// 合计数据
const getSummaries = () => {
  // console.log(param 形参);  data每一行数据 columns每一列数据

  // const { columns } = param;
  // const sums: string[] = [];
  // columns.forEach((column, index) => {
  //   sums[index] = summary.value[index];
  //   return sums;
  // });
  return summary.value;
};

// 查看状态数据
const searchResult = () => {
  initParam.detailType = stockPlanForm.value.detailType;
  proTable.value?.getTableList();
};
</script>

<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}盘点计划</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="stockPlanForm" label-width="120px" :rules="planRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="单据号" prop="orderNo">
        <el-input class="width160" v-model="stockPlanForm.orderNo" disabled placeholder="系统自动生成" />
      </el-form-item>
      <!-- <el-form-item label="盘点范围" prop="planType">
        <el-select class="width150" v-model="stockPlanForm.planType" :disabled="documentStatus !== 'add'">
          <el-option v-for="item in typeScopeList" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="仓库" prop="houseId">
        <el-select class="width150" :disabled="documentStatus !== 'add'" @change="selectChange" v-model="stockPlanForm.houseId">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          :disabled="documentStatus === 'audited'"
          class="width150"
          v-model="stockPlanForm.remark"
          placeholder="请填写"
          :rows="1"
          type="textarea"
        />
      </el-form-item>

      <!-- 只要未审核都要显示盘点清零 -->
      <el-form-item label="漏盘清零">
        <el-checkbox :disabled="stockPlanForm.status === 4" v-model="stockPlanForm.isClean"></el-checkbox>
      </el-form-item>

      <!-- 审查完查询状态 -->
      <el-form-item label="盘点结果" prop="detailType" v-if="documentStatus !== 'add'">
        <el-select class="width150" v-model="stockPlanForm.detailType">
          <el-option v-for="item in detailTypeNameType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <!-- tool-button:自定头部右侧的按钮 -->
    <!--
      :request-api="getDetailPlanPageList"
      :init-param="initParam"
      :data-callback="dataCallback"
    -->
    <ProTable
      v-if="documentStatus === 'add'"
      ref="proTableAdd"
      row-key="id"
      :columns="columns"
      :is-card="false"
      :pagination="false"
      :data="stockPlanForm.inventoryplandetailList"
    >
      <template #tableHeader>
        <el-button type="primary" @click="openSelectTreeTable('选择原料')"> 添加原料明细 </el-button>
      </template>
      <template #toolButton>
        <!-- 盘点计划没有审核，盘点单里面可以获取到盘点计划的进行盘点 -->
        <!-- <el-button v-if="stockPlanForm.status === 1 || documentStatus === 'add'" type="primary" @click="onCheckSubmit">
          保存并审核
        </el-button> -->
        <el-button @click="onSubmit" type="primary"> 保存 </el-button>
        <!-- <el-button v-if="stockPlanForm.status === 3" @click="onSubmit" type="primary"> 审核 </el-button> -->
        <el-button @click="router.go(-1)"> 返回 </el-button>
      </template>

      <template #operate="scope">
        <div class="flx-justify-between">
          <el-icon size="18" color="#169D82" @click="openSelectTreeTable('选择原料')"><Plus /></el-icon>
          <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
        </div>
        <!-- <div v-else>--</div> -->
      </template>
    </ProTable>
    <!-- :tool-button="documentStatus !== 'audited'" -->
    <ProTable
      v-else
      ref="proTable"
      row-key="id"
      :columns="columns"
      :is-card="false"
      :request-api="getDetailPlanPageList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :show-summary="documentStatus === 'audited'"
      :summary-method="getSummaries"
    >
      <!-- <template #tableHeader>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择原料')">
          添加原料明细
        </el-button>
      </template> -->
      <template #toolButton>
        <!-- 盘点计划没有审核，盘点单里面可以获取到盘点计划的进行盘点 -->
        <!-- <el-button v-if="stockPlanForm.status === 1 || documentStatus === 'add'" type="primary" @click="onCheckSubmit">
          保存并审核
        </el-button> -->
        <el-button type="primary" @click="searchResult"> 查询盘点结果 </el-button>

        <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
        <el-button v-if="stockPlanForm.status === 2" @click="onCheckSubmit" type="primary"> 完成盘点 </el-button>
        <el-button @click="router.go(-1)"> 返回 </el-button>
      </template>
    </ProTable>

    <SelectTreeTable ref="selectTreeTableRef" @selected-list="handleSelectedTreeList"></SelectTreeTable>

    <!-- 盘点明细 -->

    <!--
          // 数据已审核需要渲染详情
          // const inventory = ref([]);
          // const stockDetailList = ref([
          //   { label: "全部", list: [], name: "first" },
          //   { label: "盘平", list: [], name: "second" },
          //   { label: "盘盈", list: [], name: "third" },
          //   { label: "盘亏", list: [], name: "fourth" }
          // ]);    
          // 以前盘亏分类列表数据 if (res.data.inventory) {
         //   inventory.value = [{ ...JSON.parse(JSON.stringify(res.data.inventory)) }];

        //   stockDetailList.value[0].list = JSON.parse(JSON.stringify(res.data.  inventory.inventorydetailList));
       //   res.data.inventory.inventorydetailList.forEach(v => {
       //     if (v.detailType === -1) {
       //       stockDetailList.value[3]?.list.push(v);
       //     } else if (v.detailType === 1) {

       //       stockDetailList.value[2]?.list.push(v);
       //     } else {

       //       stockDetailList.value[1]?.list.push(v);
       //     }
       //   });
       // }
      // 盘点明细
      // const activeName = ref("first");
      <div v-if="documentStatus === 'audited'">
      <div style="padding: 20px 20px 0; color: #fdc31d">盘点单据</div>
      <hr style="border: 1px solid #e4e7ed" />

      <el-table border :data="inventory" style="width: 100%; height: 30%">
        <el-table-column align="center" prop="orderNo" label="单据号" width="250" />
        <el-table-column align="center" prop="checkFlagName" label="状态" width="250"> </el-table-column>
        <el-table-column align="center" prop="sysUserId" label="制单人" />
        <el-table-column align="center" prop="createTime" label="制单日期" />
        <el-table-column align="center" prop="checkerId" label="审核人" />
        <el-table-column align="center" prop="checkTime" label="审核日期" />
        <el-table-column align="center" prop="quantity" label="盈亏数量" />
        <el-table-column align="center" prop="amount" label="成本价" />
      </el-table>

      <div style="padding: 20px 20px 0; color: #fdc31d">盘点明细</div>
      <hr style="border: 1px solid #e4e7ed" />
      <el-tabs v-model="activeName" class="demo-tabs">
         基础信息
        <el-tab-pane v-for="item in stockDetailList" :label="item.label" :name="item.name" :key="item.name">
          <el-table border :data="item.list" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="id" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="categoryName" label="原料分类" />
            <el-table-column align="center" prop="unitName" label="单位" />
            <el-table-column align="center" prop="realQuantity" label="实盘数量" />
            <el-table-column align="center" prop="planQuantity" label="账面数量" />
            <el-table-column align="center" prop="profitLossQuantity" label="盈亏数量" />
            <el-table-column align="center" prop="costPrice" label="成本价" />
            <el-table-column align="center" prop="profitLossAmount" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <<el-tab-pane label="盘平" name="second">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="原料分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="盘盈" name="third">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="原料分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="盘亏" name="fourth">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="原料分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="漏盘" name="fifth">
          <el-table border :data="tableData" style="width: 100%; height: 80%">
            <el-table-column align="center" prop="date" label="条码" width="250" />
            <el-table-column align="center" prop="name" label="名称" width="250" />
            <el-table-column align="center" prop="address" label="原料分类" />
            <el-table-column align="center" prop="address" label="单位" />
            <el-table-column align="center" prop="address" label="实盘数量" />
            <el-table-column align="center" prop="address" label="账面数量" />
            <el-table-column align="center" prop="address" label="盈亏数量" />
            <el-table-column align="center" prop="address" label="成本价" />
            <el-table-column align="center" prop="address" label="盈亏金额" />
          </el-table>
        </el-tab-pane> 
        <el-tab-pane name="sixth">
          <template #label>
            <el-checkbox>漏盘原料清零</el-checkbox>
          </template>
        </el-tab-pane> 
      </el-tabs>
    </div> -->
  </div>
</template>

<style lang="scss" scoped></style>
